<template>
  <div class="bg-white rounded-2xl shadow-sm ring-1 ring-gray-200 p-5 hover:shadow-md transition relative">
    <button
      class="absolute right-4 top-4 text-sm text-amber-500 hover:text-amber-600"
      @click.stop="toggleFavorite"
      :title="isFavorited ? '取消收藏' : '收藏'"
    >
      {{ isFavorited ? '★ 已收藏' : '☆ 收藏' }}
    </button>
    <div class="w-16 h-16 rounded-full overflow-hidden">
      <RobustImage 
        :src="image"
        :alt="name"
        class="w-full h-full object-cover rounded-full"
        :fallback-text="name"
        :enable-retry="true"
        :max-retries="3"
      />
    </div>
    <div class="mt-3">
      <div class="text-gray-900 font-semibold">{{ name }}</div>
      <p class="mt-1 text-sm text-gray-500 overflow-hidden" style="display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; line-clamp: 2;">{{ intro }}</p>
    </div>
    <div class="mt-3 flex flex-wrap gap-2">
      <span v-for="t in tagList" :key="t" class="px-2 h-6 rounded-md bg-gray-100 text-gray-600 text-xs inline-flex items-center">{{ t }}</span>
    </div>
    <div class="mt-2 flex items-center gap-4 text-xs text-gray-500">
      <!-- <span>📊 {{ viewCount }}</span> -->
      <!-- <span>⭐ {{ isFavorited ? '已收藏' : '未收藏' }}</span> -->
    </div>
    <RouterLink :to="`/details/${id}`" class="mt-4 w-full h-10 rounded-lg bg-[#635BFF] text-white text-sm flex items-center justify-center gap-2">
      <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 4.663 12 5.109 12 6v12c0 .891-1.077 1.337-1.707.707L5.586 15z" />
      </svg>
      开始对话
    </RouterLink>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import type { RoleInfo } from '@/api/interface'
import { characterInfo } from '@/api'
import RobustImage from '@/components/RobustImage.vue'

const props = defineProps<RoleInfo>()

// 本地收藏态（避免直接改 props）
const localFavorited = ref(!!props.isFavorited)
const isFavorited = computed(() => localFavorited.value)

const toggleFavorite = async () => {
  try {
    if (localFavorited.value) {
      const res = await characterInfo.unfavorite(props.id)
      if (res?.code === 0) localFavorited.value = false
    } else {
      const res = await characterInfo.favorite(props.id)
      if (res?.code === 0) localFavorited.value = true
    }
  } catch (e) {
    console.error('切换收藏失败:', e)
  }
}


// 处理标签显示
const tagList = computed(() => {
  if (!props.tags) return []
  // 处理tags可能是字符串或数组的情况
  if (Array.isArray(props.tags)) {
    return props.tags.filter(tag => tag && tag.trim())
  }
  return props.tags.split(',').filter(tag => tag.trim())
})
</script>


